class Page < ActiveRecord::Base
  has_many :page_menu_options, :dependent => :destroy
  before_save :fix_permalink
  attr_accessible :breadcrumb, :title, :content, :is_home, :permalink, :is_featured
  
  validates_presence_of :breadcrumb, :title, :content,:permalink
  validates_length_of :breadcrumb, :maximum=>20
  
  
  def fix_permalink
    self.permalink = self.permalink.gsub(/[^a-zA-Z0-9\-_]/,"-").downcase
    page = Page.find_by_permalink(self.permalink)
    if page and page.id!=self.id
      self.permalink = self.permalink+"-"+Time.now.to_i.to_s
    end
  end
  
  def self.featured_page
    pages = Page.find_all_by_is_featured(true)
    page = nil
    if pages.size > 0
      page = pages[rand(pages.size)]
    end
    page
  end
  #Check if it has a permalink
  #unless self.permalink and self.title
  #  #generate_permalink
  #  self.permalink = self.title.gsub(/[^a-zA-Z0-9\-_]/,"-").downcase
  #  if Page.find_by_permalink(self.permalink)
  #    self.permalink = self.permalink+"-"+Time.now.to_i.to_s
  #    #end
  #  else
  #    self.permalink = self.title.gsub(/[^a-zA-Z0-9\-_]/,"-").downcase
  #  end 
  #end
  
  
end
